package mapEditor.data
{
	import flash.events.EventDispatcher;
	import flash.utils.Dictionary;
	
	import mapEditor.events.MapEditorEvent;
	import mapEditor.vo.AssetGroupVO;
	import mapEditor.vo.AssetVO;
	
	import utils.DisplayUtil;

	public class AssetTemplateInfo extends EventDispatcher
	{
		private var _templateXml:XML;
		/**
		 *资源所有资源列表 
		 */		
		private var _groups:Vector.<AssetGroupVO>=new Vector.<AssetGroupVO>();
		/**
		 *当前最大资源ID 
		 */		
		private var _maxAssetID:int;
		
		public function AssetTemplateInfo()
		{
		}
		
		private static var _instance:AssetTemplateInfo;
		public static function get instance():AssetTemplateInfo
		{
			if(_instance == null)
			{
				_instance = new AssetTemplateInfo();
			}
			return _instance;
		}
		
		public function register(xml:XML):void
		{
			dispose();
			_templateXml=xml;
			for each(var groupItem:XML in _templateXml.group)
			{
				var assetGroupVO:AssetGroupVO=new AssetGroupVO(groupItem);
				_groups.push(assetGroupVO);
			}
			assetGroupChange();
		}
		
		/**
		 *增加一个资源
		 * @param groupPath 组资源项路径
		 * @param assetVO 资源项
		 * 
		 */		
		public function addAsset(groupPath:String, assetVO:AssetVO):void
		{
			var assetGroupVO:AssetGroupVO=getGroupByPath(groupPath);
			if(!assetGroupVO)
			{
				assetGroupVO=new AssetGroupVO();
				assetGroupVO.path=groupPath;
				_groups.push(assetGroupVO);
			}
			_maxAssetID+=1;
			assetVO.id=_maxAssetID;
			assetGroupVO.addAssetVO(assetVO);
		}
		
		/**
		 *移除一个资源 
		 * @param groupPath 组资源项路径
		 * @param assetVO 资源项
		 * 
		 */		
		public function removeAsset(groupPath:String, assetVO:AssetVO):void
		{
			var assetGroupVO:AssetGroupVO=getGroupByPath(groupPath);
			assetGroupVO.removeAssetVO(assetVO);
		}
		
		public function getGroupByPath(groupPath:String):AssetGroupVO
		{
			for each(var assetGroupVO:AssetGroupVO in _groups)
			{
				if(assetGroupVO.path==groupPath)return assetGroupVO;
			}
			return null;
		}
		
		public function getAssetVOByID(id:int):AssetVO
		{
			var assetVO:AssetVO;
			for each(var assetGroupVO:AssetGroupVO in _groups)
			{
				assetVO=assetGroupVO.getAssetVOByID(id);
				if(assetVO)break;
			}
			return assetVO;
		}
		
		public function assetGroupChange():void
		{
			dispatchEvent(new MapEditorEvent(MapEditorEvent.ASSET_GROUP_CHANGE));
		}
		
		public function dispose():void
		{
			_templateXml=null;
			while(_groups && _groups.length>0)
			{
				DisplayUtil.dispose(_groups.shift());
			}
		}

		/**
		 *资源所有资源列表  
		 */
		public function get groups():Vector.<AssetGroupVO>
		{
			return _groups;
		}

		/**
		 *当前最大资源ID 
		 */
		public function get maxAssetID():int
		{
			return _maxAssetID;
		}

		/**
		 * @private
		 */
		public function set maxAssetID(value:int):void
		{
			_maxAssetID = value;
		}


	}
}